package com.hctforgreen.greenservice.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.model.MessagesListEntity.MessagesEntity;

/**
 * 数据库操作类
 * 
 * @author ld 20131122
 * 
 */
public class DBFeedbackInfoManager {
	private DBHelper helper;
	private SQLiteDatabase db;
	private static final String TABLE_FEEDBACK_INFO = "table_feedback_info";

	public DBFeedbackInfoManager(Context context) {
		helper = new DBHelper(context);
		// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
		// mFactory);
		// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
		db = helper.getWritableDatabase();

	}

	/**
	 * add messages
	 * 
	 * @param msgs
	 */
	public void add(List<FeedBackEntity> msgs) {
		db.beginTransaction(); // 开始事务
		try {
			for (FeedBackEntity msg : msgs) {
				db.execSQL("INSERT INTO " + TABLE_FEEDBACK_INFO
						+ " VALUES(?,?, ?, ?, ?, ?,?,?)", new Object[] { null,
						msg.submitDate, msg.seriesName, msg.answerContent,
						msg.videoPath, msg.picPathes, msg.answerName,
						msg.uploadFilePath });
			}
			db.setTransactionSuccessful(); // 设置事务成功完成

		} catch (Exception e) {// 主键冲突异常
			e.printStackTrace();
		} finally {
			db.endTransaction(); // 结束事务
		}
	}

	/**
	 * add messages
	 * 
	 * @param msgs
	 */
	public void delete(List<FeedBackEntity> msgs) {
		db.beginTransaction(); // 开始事务
		try {
			for (FeedBackEntity msg : msgs) {
				db.execSQL("delete from " + TABLE_FEEDBACK_INFO
						+ " where id=? ", new Object[] { msg.id });

			}
			db.setTransactionSuccessful(); // 设置事务成功完成

		} catch (Exception e) {// 主键冲突异常
			e.printStackTrace();
		} finally {
			db.endTransaction(); // 结束事务
		}
	}

	/**
	 * add message
	 * 
	 * @param msg
	 */
	public void add(FeedBackEntity msg) {

		db.beginTransaction(); // 开始事务
		try {
			db.execSQL("INSERT INTO " + TABLE_FEEDBACK_INFO
					+ " VALUES(?,?, ?, ?, ?, ?,?,?)", new Object[] { null,
					msg.submitDate, msg.seriesName, msg.answerContent,
					msg.videoPath, msg.picPathes, msg.answerName,
					msg.uploadFilePath });
			db.setTransactionSuccessful(); // 设置事务成功完成
		} finally {
			db.endTransaction(); // 结束事务
		}
	}

	public void updateMsg(FeedBackEntity msg) {
		db.beginTransaction(); // 开始事务
		try {
			db.execSQL("UPDATE " + TABLE_FEEDBACK_INFO
					+ " set date=? ,seriesName=? ,content=?," + "videoPath=? ,"
					+ "filePathes=? ," + "uploadFilePath=?, " + "title=? "
					+ "where id=?", new Object[] { msg.submitDate,
					msg.seriesName, msg.answerContent, msg.videoPath,
					msg.picPathes, msg.uploadFilePath, msg.answerName, msg.id });
			db.setTransactionSuccessful(); // 设置事务成功完成
		} finally {
			db.endTransaction(); // 结束事务
		}

	}

	public MessagesEntity setMessageReadStatus(MessagesEntity entity) {
		if (entity == null) {
			return entity;
		}
		try {
			Cursor cursor = db.rawQuery("SELECT readStatus rs FROM "
					+ TABLE_FEEDBACK_INFO + " WHERE id=?",
					new String[] { entity.id });
			if (cursor != null && cursor.getColumnCount() > 0) {
				cursor.moveToFirst();
				entity.readStatus = cursor.getInt(cursor.getColumnIndex("rs"));
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	// /**
	// * update warn's content
	// *
	// * @param person
	// */
	// public void updateAge(PwdEntity pwd) {
	// ContentValues cv = new ContentValues();
	// // cv.put("content", pwd.Content);
	// // cv.put("day", pwd.day);
	// // db.update(TABLE_WARN, cv, "_id = ?", new
	// // String[]{String.valueOf(warn._id)});
	// }

	/**
	 * delete old warn
	 * 
	 * @param person
	 */
	public void delete(FeedBackEntity entity) {
		db.delete(TABLE_FEEDBACK_INFO, "id = ?",
				new String[] { String.valueOf(entity.id) });
	}

	/**
	 * query all warns, return list
	 * 
	 * @return List<MessagesEntity>
	 */
	public List<FeedBackEntity> queryAll() {
		ArrayList<FeedBackEntity> msgs = new ArrayList<FeedBackEntity>();
		Cursor c = queryTheCursor();
		try {
			while (c.moveToNext()) {
				FeedBackEntity msg = new FeedBackEntity();
				msg.id = c.getString(c.getColumnIndex("id"));
				msg.picPathes = c.getString(c.getColumnIndex("filePathes"));
				msg.content = c.getString(c.getColumnIndex("content"));
				msg.title = c.getString(c.getColumnIndex("title"));
				msg.seriesName = c.getString(c.getColumnIndex("seriesName"));
				msg.videoPath = c.getString(c.getColumnIndex("videoPath"));
				msg.submitDate = c.getString(c.getColumnIndex("date"));
				msg.uploadFilePath = c.getString(c
						.getColumnIndex("uploadFilePath"));
				if (msg.picPathes != null && !"".equals(msg.picPathes.trim())) {
					String[] pics = msg.picPathes
							.split(FeedBackEntity.PIC_FILE_SEPRATOR);
					if (pics != null && pics.length > 0) {
						for (String string : pics) {
							msg.picNames.add(string);
						}
					}
				}
				msgs.add(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		c.close();
		return msgs;
	}

	/**
	 * query all warns, return cursor
	 * 
	 * @return Cursor
	 */
	public Cursor queryTheCursor() {
		Cursor c = db.rawQuery("SELECT * FROM " + TABLE_FEEDBACK_INFO
				+ " order by date desc", null);
		return c;
	}

	//
	// /**
	// * query all warns, return list
	// *
	// * @return List<Person>
	// */
	// public List<PwdEntity> queryByDate(String date) {
	// ArrayList<PwdEntity> pwds = new ArrayList<PwdEntity>();
	// Cursor c = fetchFromDate(date);
	// while (c.moveToNext()) {
	// PwdEntity pwd = new PwdEntity();
	// pwd._id = c.getInt(c.getColumnIndex("_id"));
	// pwd.stripeCode = c.getString(c.getColumnIndex("stripeCode"));
	// pwd.openPassword = c.getString(c.getColumnIndex("openPassword"));
	// pwd.projectName = c.getString(c.getColumnIndex("projectName"));
	// pwd.ownerName = c.getString(c.getColumnIndex("ownerName"));
	// pwd.ownerPhone = c.getString(c.getColumnIndex("ownerPhone"));
	// pwd.note = c.getString(c.getColumnIndex("note"));
	// pwd.date = c.getString(c.getColumnIndex("date"));
	// pwd.time = c.getString(c.getColumnIndex("time"));
	// pwd.province = c.getString(c.getColumnIndex("province"));
	// pwd.city = c.getString(c.getColumnIndex("city"));
	// pwd.district = c.getString(c.getColumnIndex("district"));
	// pwd.street = c.getString(c.getColumnIndex("street"));
	// pwds.add(pwd);
	// }
	// c.close();
	// return pwds;
	// }

	// 查询指定fund数据data
	public Cursor fetchFromDate(String date) throws SQLException {
		String sql = "SELECT * FROM " + TABLE_FEEDBACK_INFO + " WHERE "
				+ "date" + " = ?" + " order by _id desc";
		Cursor cursor = db.rawQuery(sql, new String[] { date });
		return cursor;
	}

	/**
	 * close database
	 */
	public void closeDB() {
		db.close();
	}

}
